//
//  GoodsDetailViewController.swift
//  WangPu
//
//  Created by xiaozhi on 15/9/21.
//  Copyright (c) 2015年 zhixiao. All rights reserved.
//

import UIKit

class GoodsDetailViewController: BaseViewController {
    var scrollView:UIScrollView!
    var topScrollView:UIScrollView!
    var bottomScrollView:UIScrollView!
    var bottomView:UIView!
    var imageScrollView:UIScrollView!
    var pageControl:UIPageControl!
    var goodsID:String?
    var webView:UIWebView!
    var loveBtn:MyButton!
    var showUpBtn:UIButton!
    var addBtn:UIButton!
    var cartBtn:MyButton!
     let scrollHeight = windowHeight-64-49
    var dataItem:GoodDetailItem?
    override func viewDidLoad() {
        super.viewDidLoad()

//        self.navigationController?.navigationBarHidden = false
        self.title = "商品详情"
        let backItem = UIBarButtonItem(image: UIImage(named: "back_icon"), style:UIBarButtonItemStyle.Plain, target:self, action:"goBack")
        backItem.tintColor = UIColor.whiteColor()
        self.navigationItem.leftBarButtonItem = backItem
        self.automaticallyAdjustsScrollViewInsets = false
       
        scrollView = UIScrollView(frame: CGRectMake(0, 64, windowWidth, scrollHeight))
        scrollView.scrollEnabled = false
        scrollView.pagingEnabled = true
        scrollView.backgroundColor = UIColor.whiteColor()
        scrollView.contentSize = CGSizeMake(windowWidth, scrollHeight*2)
        view.addSubview(scrollView)
        
        showUpBtn = UIButton(frame: CGRectMake(view.bounds.size.width-50, view.bounds.size.height-49-50, 36, 37))
        showUpBtn.backgroundColor = UIColor.clearColor()
        showUpBtn.layer.cornerRadius = 4.0
        showUpBtn.setBackgroundImage(UIImage(named: "push--button"), forState: UIControlState.Normal)
        showUpBtn.addTarget(self, action: "showTop", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(showUpBtn)
        showUpBtn.hidden = true
        
        topScrollView = UIScrollView(frame: CGRectMake(0, 0, windowWidth, scrollHeight))
        topScrollView.delegate = self
//        topScrollView.contentSize = CGSizeMake(windowWidth, windowHeight+64)
        scrollView.addSubview(topScrollView)
//        topScrollView.footer = MJRefreshAutoNormalFooter(refreshingBlock:{
//            UIView.animateWithDuration(0.5, delay: 0.0,
//                options: UIViewAnimationOptions.LayoutSubviews,
//                animations:{
//                    self.scrollView.setContentOffset(CGPointMake(0, windowHeight), animated: true)
//                },
//                completion:{
//                    finished in self.topScrollView.footer.endRefreshing()
//            })
//        })
        bottomScrollView = UIScrollView(frame: CGRectMake(0, scrollHeight, windowWidth,scrollHeight))
        scrollView.addSubview(bottomScrollView)

        
        
        bottomScrollView.header = MJRefreshNormalHeader(refreshingBlock: {
            UIView.animateWithDuration(0.5, delay: 0.0,
                options: UIViewAnimationOptions.LayoutSubviews,
                animations:{
                    self.scrollView.setContentOffset(CGPointMake(0, 0), animated: true)
                    self.showUpBtn.hidden = true
                },
                completion:{
                    finished in self.bottomScrollView.header.endRefreshing()
            })
        })
        if let head = bottomScrollView.header as? MJRefreshNormalHeader{
            head.lastUpdatedTimeLabel?.hidden = true
            head.setTitle("下拉可以返回", forState: MJRefreshStateIdle)
            head.setTitle("放开即可返回", forState: MJRefreshStatePulling)
            head.setTitle("", forState: MJRefreshStateRefreshing)
            head.setTitle("", forState: MJRefreshStateWillRefresh)
        }
        self.queryGoodsByID(goodsID)
        self.setupBottomView()
        // Do any additional setup after loading the view.
    }
    func showBottomContent()->Void{
        UIView.animateWithDuration(0.5, delay: 0.0,
            options: UIViewAnimationOptions.LayoutSubviews,
            animations:{
                self.scrollView.setContentOffset(CGPointMake(0, self.scrollHeight), animated: true)
                self.showUpBtn.hidden = false
            },
            completion:nil)
    }
    func showTopContent()->Void{
        UIView.animateWithDuration(0.5, delay: 0.0,
            options: UIViewAnimationOptions.LayoutSubviews,
            animations:{
                self.scrollView.setContentOffset(CGPointMake(0, 0), animated: true)
                self.showUpBtn.hidden = true

            },
            completion:{
                finished in self.bottomScrollView.header.endRefreshing()
        })
    }
    func showTop()->Void{
        self.showTopContent()
    }
    func layoutTopScrollView()->Void{
        imageScrollView = UIScrollView(frame: CGRectMake(0, 5, view.bounds.size.width, 150))
        imageScrollView.showsHorizontalScrollIndicator=false
        imageScrollView.showsVerticalScrollIndicator = false
//        imageScrollView.backgroundColor = UIColor(red: 246/255.0, green: 246/255.0, blue: 246/255.0, alpha: 1.0)
//        imageScrollView.backgroundColor = UIColor.orangeColor()

        imageScrollView.pagingEnabled = true
        imageScrollView.delegate = self
        pageControl = UIPageControl()

        var tapImageView:TapImageView!
        if let imageArray = self.dataItem?.litterImage{
            imageScrollView.contentSize = CGSizeMake(view.bounds.size.width*CGFloat(imageArray.count), 150)
            for i in 0..<imageArray.count{
                let originX = CGFloat(i)*view.bounds.size.width
                tapImageView = TapImageView(frame: CGRectMake(originX, 0, view.bounds.size.width, 150))
                var iamgeurl:String = ""
                if let dic = imageArray[i] as? NSDictionary{
                    iamgeurl = dic["thumbnail"]! as! String
                }
                tapImageView.setImageWithUrl(iamgeurl, defaultImage: nil)
                tapImageView.contentMode = UIViewContentMode.ScaleAspectFill
                tapImageView.id = "\(i+1)"
                tapImageView.TapCompelete = {[weak self]id in
                    let ctl = ShowImageViewController()
                    ctl.imageurl = iamgeurl
                    self?.navigationController?.pushViewController(ctl, animated: true)
                }
                imageScrollView.addSubview(tapImageView)
            }
            topScrollView.addSubview(imageScrollView)

            pageControl.frame = CGRectMake(0, CGRectGetMaxY(imageScrollView.frame)-30, imageScrollView.bounds.size.width, 30)
            pageControl.numberOfPages = self.dataItem!.litterImage!.count
            pageControl.currentPage = 0
            pageControl.pageIndicatorTintColor = UIColor.blackColor()
            pageControl.currentPageIndicatorTintColor = UIColor.whiteColor()
            pageControl.addTarget(self, action: "pageTurn:", forControlEvents: UIControlEvents.ValueChanged)
            topScrollView.addSubview(pageControl)
        }


        //名称
        let offsetX:CGFloat = 5.0
        let offsetY:CGFloat = 10.0
        let nameLabel = UILabel(frame: CGRectMake(offsetX, CGRectGetMaxY(imageScrollView.frame)+offsetY, topScrollView.bounds.size.width-10, 36))
        nameLabel.numberOfLines = 0;
        
        nameLabel.text = self.dataItem?.name
//        noteLabel.textColor = UIColor.lightGrayColor()
        nameLabel.textAlignment = NSTextAlignment.Left
        nameLabel.font = UIFont.systemFontOfSize(14)
        topScrollView.addSubview(nameLabel)
        //price
        let priceLabel = UILabel(frame: CGRectMake(offsetX, CGRectGetMaxY(nameLabel.frame)+offsetY,120, 20))
        priceLabel.numberOfLines = 0;
        priceLabel.text = "¥"+self.dataItem!.price!
        priceLabel.textColor = commonRedColor
        priceLabel.textAlignment = NSTextAlignment.Left
        priceLabel.font = UIFont.systemFontOfSize(14)
        topScrollView.addSubview(priceLabel)
        //reduce price note buttton
//        let noteButton = UIButton(frame: CGRectMake(topScrollView.bounds.size.width-90, CGRectGetMaxY(nameLabel.frame)+5, 80, 26))
//        noteButton.setTitle("降价通知", forState: UIControlState.Normal)
//        noteButton.titleLabel?.font = UIFont.boldSystemFontOfSize(14)
//        noteButton.titleLabel?.textAlignment = NSTextAlignment.Center
//        noteButton.setTitleColor(commonRedColor, forState: UIControlState.Normal)
//        noteButton.layer.cornerRadius = 4
//        noteButton.layer.borderColor = commonRedColor.CGColor
//        noteButton.layer.borderWidth = onePix
//        topScrollView.addSubview(noteButton)
        //seperator line
        let line:DotView = DotView(frame: CGRectMake(offsetX, CGRectGetMaxY(priceLabel.frame)+offsetY, topScrollView.bounds.size.width-10, 1))
        line.cutNumber = 300
        line.storkeDot()
        topScrollView.addSubview(line)
        //属性标签
        let array:[String?] = ["正品保障","全程透明","售后无忧"]
        for i in 0..<array.count{
            let igv = UIImageView(frame: CGRectMake(offsetX+(8+80)*CGFloat(i), CGRectGetMaxY(line.frame)+offsetY+5, 9, 9))
            igv.image = UIImage(named: "zheng_icon")
            topScrollView.addSubview(igv)
            let lbl = UILabel(frame: CGRectMake((8+80)*CGFloat(i)+16+offsetX, CGRectGetMaxY(line.frame)+offsetY,80, 20))
            lbl.text = array[i];
//            lbl.textColor = commonRedColor
            lbl.font = UIFont.systemFontOfSize(12)
            topScrollView.addSubview(lbl)
        }
        //分割line
        var sepView = UIView(frame: CGRectMake(0, CGRectGetMaxY(line.frame)+40, topScrollView.bounds.size.width, 10))
        sepView.backgroundColor = view.backgroundColor
        topScrollView.addSubview(sepView)
        //goods参数
        let goodsButton = UIButton(frame: CGRectMake(offsetX, CGRectGetMaxY(sepView.frame)+5, topScrollView.bounds.size.width-offsetX-offsetX, 35))
        topScrollView.addSubview(goodsButton)
        let lbl1 = UILabel(frame: CGRectMake(0, 0,80, goodsButton.bounds.size.height))
//        lbl1.text = "现货"
        if self.dataItem?.isSaleable == "1"{
            lbl1.text = "现货"
        }
        else{
            lbl1.text = "无货"
        }
        lbl1.textColor = commonRedColor
        lbl1.textAlignment = NSTextAlignment.Left
        lbl1.font = UIFont.systemFontOfSize(14)
        goodsButton.addSubview(lbl1)
        

        if self.dataItem?.deliverytime != ""{
            let lbl2 = UILabel(frame: CGRectMake(CGRectGetMaxX(lbl1.frame)+10, 0,180, goodsButton.bounds.size.height))
            lbl2.text = (self.dataItem?.deliverytime!)! + "天"
            //        lbl2.textColor = commonRedColor
            lbl2.textAlignment = NSTextAlignment.Left
            lbl2.font = UIFont.systemFontOfSize(14)
            goodsButton.addSubview(lbl2)
        }

        
//        let accButton = FRDLivelyButton(frame: CGRectMake(goodsButton.bounds.size.width-40, 5, 40, goodsButton.bounds.size.height-10))
//        accButton.options = [
//                kFRDLivelyButtonColor: UIColor.lightGrayColor(),
//                kFRDLivelyButtonHighlightedColor: UIColor.clearColor(),
//                kFRDLivelyButtonHighlightAnimationDuration: (0.1),
//                kFRDLivelyButtonHighlightScale: (0.9),
//                kFRDLivelyButtonLineWidth: (1.0),
//                kFRDLivelyButtonUnHighlightAnimationDuration: (0.15),
//                kFRDLivelyButtonStyleChangeAnimationDuration: (0.3)
//        ]
//        accButton.userInteractionEnabled = false;
//        accButton.setStyle(kFRDLivelyButtonStyleCaretRight, animated: false)
//        goodsButton.addSubview(accButton)
        sepView = UIView(frame: CGRectMake(0, CGRectGetMaxY(goodsButton.frame), topScrollView.bounds.size.width, onePix))
        sepView.backgroundColor = view.backgroundColor
        topScrollView.addSubview(sepView)
        //xianhuo
        let lbl3 = UILabel(frame: CGRectMake(5, CGRectGetMaxY(goodsButton.frame),80, 0))
//        if self.dataItem?.isSaleable == "1"{
//            lbl3.text = "现货"
//        }
//        else{
//            lbl3.text = "无货"
//        }
        lbl3.textColor = commonRedColor
        lbl3.textAlignment = NSTextAlignment.Left
        lbl3.font = UIFont.systemFontOfSize(14)
        topScrollView.addSubview(lbl3)
        
        let lbl4 = UILabel(frame: CGRectMake(CGRectGetMaxX(lbl3.frame)+10, CGRectGetMaxY(goodsButton.frame),180, 0))
        lbl4.textColor = UIColor.lightGrayColor()
        lbl4.textAlignment = NSTextAlignment.Center
        lbl4.font = UIFont.systemFontOfSize(14)
        topScrollView.addSubview(lbl4)

        //fenge 
        sepView = UIView(frame: CGRectMake(0, CGRectGetMaxY(lbl4.frame), topScrollView.bounds.size.width, 10))
        sepView.backgroundColor = view.backgroundColor
        topScrollView.addSubview(sepView)
        //好评
        let goodsCommentButton = UIButton(frame: CGRectMake(offsetX, CGRectGetMaxY(sepView.frame)+5, topScrollView.bounds.size.width-offsetX-offsetX, 35))
        topScrollView.addSubview(goodsCommentButton)
        let lbl5 = UILabel(frame: CGRectMake(0, 0,50, goodsButton.bounds.size.height))
        lbl5.text = "好评"
//        lbl5.textColor = UIColor.lightGrayColor()
        lbl5.textAlignment = NSTextAlignment.Left
        lbl5.font = UIFont.systemFontOfSize(14)
        goodsCommentButton.addSubview(lbl5)
        
        let lbl6 = UILabel(frame: CGRectMake(CGRectGetMaxX(lbl5.frame), 0,60, goodsButton.bounds.size.height))
        lbl6.text = self.dataItem!.rating_avg! + "%"
        lbl6.textColor = commonRedColor
        lbl6.textAlignment = NSTextAlignment.Left
        lbl6.font = UIFont.systemFontOfSize(14)
        goodsCommentButton.addSubview(lbl6)
        
        let lbl7 = UILabel(frame: CGRectMake(CGRectGetMaxX(lbl6.frame), 0,120, goodsButton.bounds.size.height))
        lbl7.text = self.dataItem!.review_total! + "人评论"
        lbl7.textColor = UIColor.lightGrayColor()
        lbl7.textAlignment = NSTextAlignment.Center
        lbl7.font = UIFont.systemFontOfSize(14)
        goodsCommentButton.addSubview(lbl7)
        
        let comButton = FRDLivelyButton(frame: CGRectMake(goodsButton.bounds.size.width-40, 5, 40, goodsButton.bounds.size.height-10))
        comButton.options = [
            kFRDLivelyButtonColor: UIColor.lightGrayColor(),
            kFRDLivelyButtonHighlightedColor: UIColor.clearColor(),
            kFRDLivelyButtonHighlightAnimationDuration: (0.1),
            kFRDLivelyButtonHighlightScale: (0.9),
            kFRDLivelyButtonLineWidth: (1.0),
            kFRDLivelyButtonUnHighlightAnimationDuration: (0.15),
            kFRDLivelyButtonStyleChangeAnimationDuration: (0.3)
        ]
        comButton.userInteractionEnabled = false;
        comButton.setStyle(kFRDLivelyButtonStyleCaretRight, animated: false)
        goodsCommentButton.addSubview(comButton)
        sepView = UIView(frame: CGRectMake(0, CGRectGetMaxY(goodsCommentButton.frame), topScrollView.bounds.size.width, onePix))
        sepView.backgroundColor = view.backgroundColor
        topScrollView.addSubview(sepView)
        
        //评论
        var commentobj:CommentObj = (self.dataItem?.first_commit!.parseDataToCommentItem())!
//        commentobj.detail = "skdfhalksdfoeok大量的空间发哈类似的看法哈立德是咖啡哈立德是咖啡哈里斯的"
        var aSize = CGSizeZero
        if let content = commentobj.detail{
            let contentStr = content as NSString
            aSize = contentStr.sizewithFont(UIFont.systemFontOfSize(12), maxSize:CGSizeMake(view.bounds.size.width - 30, 200))
        }
        let commentCell = CommentCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
        commentCell.frame = CGRectMake(0, CGRectGetMaxY(sepView.frame)+5, topScrollView.bounds.size.width, aSize.height + 40)
        commentCell.layoutWithData(commentobj)
        
        topScrollView.addSubview(commentCell)
        sepView = UIView(frame: CGRectMake(0, CGRectGetMaxY(commentCell.frame), topScrollView.bounds.size.width, onePix))
        sepView.backgroundColor = view.backgroundColor
        topScrollView.addSubview(sepView)
       // 查看更多
        let moreCommentButton = UIButton(frame: CGRectMake(offsetX, CGRectGetMaxY(sepView.frame)+5, topScrollView.bounds.size.width-offsetX-offsetX, 35))
        moreCommentButton.setTitle("查看更多", forState: UIControlState.Normal)
        moreCommentButton.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
        moreCommentButton.titleLabel?.font = UIFont.systemFontOfSize(14)
        moreCommentButton.addTarget(self, action: "showMoreComment", forControlEvents: UIControlEvents.TouchUpInside)
        topScrollView.addSubview(moreCommentButton)
        let moreButton = FRDLivelyButton(frame: CGRectMake(goodsButton.bounds.size.width/2+25, 5, 40, goodsButton.bounds.size.height-10))
        moreButton.options = [
            kFRDLivelyButtonColor: UIColor.lightGrayColor(),
            kFRDLivelyButtonHighlightedColor: UIColor.clearColor(),
            kFRDLivelyButtonHighlightAnimationDuration: (0.1),
            kFRDLivelyButtonHighlightScale: (0.9),
            kFRDLivelyButtonLineWidth: (1.0),
            kFRDLivelyButtonUnHighlightAnimationDuration: (0.15),
            kFRDLivelyButtonStyleChangeAnimationDuration: (0.3)
        ]
        moreButton.userInteractionEnabled = false;
        moreButton.setStyle(kFRDLivelyButtonStyleCaretRight, animated: false)
        moreCommentButton.addSubview(moreButton)
        //fenge
        sepView = UIView(frame: CGRectMake(0, CGRectGetMaxY(moreCommentButton.frame), topScrollView.bounds.size.width, 10))
        sepView.backgroundColor = view.backgroundColor
        topScrollView.addSubview(sepView)
        //猜你喜欢
        let loveButton = UIButton(frame: CGRectMake(offsetX, CGRectGetMaxY(sepView.frame)+5, topScrollView.bounds.size.width-offsetX-offsetX, 35))
        topScrollView.addSubview(loveButton)
        let lbl8 = UILabel(frame: CGRectMake(0, 0,80, goodsButton.bounds.size.height))
        lbl8.text = "猜你喜欢"
        lbl8.textColor = UIColor.lightGrayColor()
        lbl8.textAlignment = NSTextAlignment.Left
        lbl8.font = UIFont.systemFontOfSize(14)
        loveButton.addSubview(lbl8)
        
        let lvButton = FRDLivelyButton(frame: CGRectMake(loveButton.bounds.size.width-40, 5, 40, goodsButton.bounds.size.height-10))
        lvButton.options = [
            kFRDLivelyButtonColor: UIColor.lightGrayColor(),
            kFRDLivelyButtonHighlightedColor: UIColor.clearColor(),
            kFRDLivelyButtonHighlightAnimationDuration: (0.1),
            kFRDLivelyButtonHighlightScale: (0.9),
            kFRDLivelyButtonLineWidth: (1.0),
            kFRDLivelyButtonUnHighlightAnimationDuration: (0.15),
            kFRDLivelyButtonStyleChangeAnimationDuration: (0.3)
        ]
        lvButton.userInteractionEnabled = false;
        lvButton.setStyle(kFRDLivelyButtonStyleCaretRight, animated: false)
        loveButton.addSubview(lvButton)
        
        sepView = UIView(frame: CGRectMake(0, CGRectGetMaxY(loveButton.frame), topScrollView.bounds.size.width, onePix))
        sepView.backgroundColor = view.backgroundColor
        topScrollView.addSubview(sepView)
        
        sepView = UIView(frame: CGRectMake(0, CGRectGetMaxY(sepView.frame), topScrollView.bounds.size.width, 10))
        sepView.backgroundColor = view.backgroundColor
        topScrollView.addSubview(sepView)
        //类型判断
        let acell = NSBundle.mainBundle().loadNibNamed("GoodsGridCell", owner: nil, options: nil)[0] as! GoodsGridCell
        acell.frame = CGRectMake(0, CGRectGetMaxY(sepView.frame), topScrollView.bounds.size.width, 200)
        var obj1,obj2:GoodDetailItem?
        obj1 = self.dataItem
        obj2 = self.dataItem
        acell.imageView1.setImageWithUrl(obj1!.image!, defaultImage:nil)
        acell.name1.text = obj1?.name
        acell.price1.text = "¥"+obj1!.price!
        if obj2 == nil{
            acell.cell2.hidden = true
        }
        else{
            acell.imageView2.setImageWithUrl(obj2!.image!, defaultImage:nil)
            acell.name2.text = obj2?.name
            acell.price2.text = "¥"+obj2!.price!
        }
        acell.addstrokeDelay()
        topScrollView.addSubview(acell)
//        sepView = UIView(frame: CGRectMake(0, CGRectGetMaxY(acell.frame), topScrollView.bounds.size.width, 10))
//        sepView.backgroundColor = view.backgroundColor
//        topScrollView.addSubview(sepView)
//        topScrollView.contentSize = CGSizeMake(topScrollView.bounds.size.width, CGRectGetMaxY(sepView.frame)+10)

        //上拉查看更多
        //查看更多
        let getMoreButton = UIButton(frame: CGRectMake(offsetX, CGRectGetMaxY(acell.frame)+5, topScrollView.bounds.size.width-offsetX-offsetX, 35))
        getMoreButton.setTitle("   上拉查看图文详情", forState: UIControlState.Normal)
        getMoreButton.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
        getMoreButton.titleLabel?.font = UIFont.systemFontOfSize(14)
        topScrollView.addSubview(getMoreButton)
        let arrowButton = FRDLivelyButton(frame: CGRectMake(getMoreButton.bounds.size.width/2-80, 5, 40, getMoreButton.bounds.size.height-10))
        arrowButton.options = [
            kFRDLivelyButtonColor: UIColor.lightGrayColor(),
            kFRDLivelyButtonHighlightedColor: UIColor.clearColor(),
            kFRDLivelyButtonHighlightAnimationDuration: (0.1),
            kFRDLivelyButtonHighlightScale: (0.9),
            kFRDLivelyButtonLineWidth: (1.0),
            kFRDLivelyButtonUnHighlightAnimationDuration: (0.15),
            kFRDLivelyButtonStyleChangeAnimationDuration: (0.3)
        ]
        arrowButton.userInteractionEnabled = false;
        arrowButton.setStyle(kFRDLivelyButtonStyleCaretUp, animated: false)
        getMoreButton.addSubview(arrowButton)
        sepView = UIView(frame: CGRectMake(0, CGRectGetMaxY(getMoreButton.frame), topScrollView.bounds.size.width, 10))
        sepView.backgroundColor = view.backgroundColor
        topScrollView.addSubview(sepView)
        topScrollView.contentSize = CGSizeMake(topScrollView.bounds.size.width, CGRectGetMaxY(sepView.frame)-5)

    }
    func layoutBottomScrollView()->Void{
//        let urlArray = ["http://www.baidu.com","http://www.sina.com","http://www.qq.com"]
//        let menuView = MenuView(frame: CGRectMake(0, 0, bottomScrollView.bounds.size.width, 40))
//        menuView.buttonEventHandle = {[weak self] index in
//            let urlStr = urlArray[index]
//            let url = NSURL(string: urlStr)
//            let request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 30.0)
//            self?.webView.loadRequest(request)
//        }
//        bottomScrollView.addSubview(menuView)
        webView = UIWebView(frame: CGRectMake(0, 0, bottomScrollView.bounds.size.width, bottomScrollView.bounds.size.height))
        var urlStr = ""
        if let s = self.dataItem?.description{
           urlStr = s
        }
        let url = NSURL(string:urlStr)
        let request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 30.0)
        self.webView.loadRequest(request)
        bottomScrollView.addSubview(webView)
    }
    func setupBottomView()->Void{
        bottomView = UIView(frame: CGRectMake(0, CGRectGetMaxY(scrollView.frame), view.bounds.size.width, 49))
        
        bottomView.backgroundColor = UIColor.whiteColor()
        let sepView = UIView(frame: CGRectMake(0, 0, topScrollView.bounds.size.width, onePix))
        sepView.backgroundColor = view.backgroundColor
        bottomView.addSubview(sepView)
        
        loveBtn = MyButton(frame: CGRectMake(25, 2, 40, 44))
        loveBtn.setTitle("收藏", forState: UIControlState.Normal)
        loveBtn.imageSize = CGSizeMake(16, 15)
        loveBtn.titleLabel?.textAlignment = NSTextAlignment.Center
        loveBtn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        loveBtn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        loveBtn.titleLabel?.font = UIFont.systemFontOfSize(11)

        loveBtn.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
        loveBtn.addTarget(self, action: "addToLove", forControlEvents: UIControlEvents.TouchDown)
        loveBtn.setImage(UIImage(named:"bottom_icon_collection"), forState: UIControlState.Normal)
        bottomView.addSubview(loveBtn)
        
        addBtn = UIButton(frame: CGRectMake(bottomView.bounds.size.width/2.0-60, 9, 130, 32))
        addBtn.backgroundColor = commonRedColor
        addBtn.layer.cornerRadius = 4.0
        addBtn.addTarget(self, action: "addToCart", forControlEvents: UIControlEvents.TouchUpInside)
        addBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        addBtn.setTitle("加入购物车", forState: UIControlState.Normal)
        addBtn.titleLabel?.font = UIFont.systemFontOfSize(15)
        bottomView.addSubview(addBtn)
        
        cartBtn = MyButton(frame: CGRectMake(bottomView.bounds.size.width-60-25, 2, 60, 44))
        cartBtn.imageSize = CGSizeMake(16, 15)
        cartBtn.setTitle("购物车", forState: UIControlState.Normal)
        cartBtn.titleLabel?.font = UIFont.systemFontOfSize(11)
        cartBtn.titleLabel?.textAlignment = NSTextAlignment.Center
        cartBtn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        cartBtn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        cartBtn.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
        cartBtn.addTarget(self, action: "goCart", forControlEvents: UIControlEvents.TouchDown)
        cartBtn.setImage(UIImage(named:"bottom_icon_car"), forState: UIControlState.Normal)
        bottomView.addSubview(cartBtn)
        self.view.addSubview(bottomView)
    }
    func  goLogin(){
        let ctl = LoginViewController()
        ctl.loginSuccess = { userInfo in
            GlobalDataHelper.instance.userId = userInfo?["id"] as? String
            GlobalDataHelper.instance.userInfo = userInfo
            GlobalDataHelper.instance.is_authentication = userInfo?["is_authentication"] as? String
        }
        self.navigationController?.pushViewController(ctl, animated: true)
    }
    func showMoreComment(){
        let ctl = CommentViewController()
        self.navigationController?.pushViewController(ctl, animated: true)
    }
    func  addToLove(){
        if GlobalDataHelper.instance.session == nil{
            self.goLogin()
            return
        }
        self.addGoodsToFavorite(GlobalDataHelper.instance.session, id: self.dataItem!.id!)
    }
    func  goCart(){
        
            GlobalDataHelper.instance.tabCtl?.setSelectCtl(3)
    }
    func  addToCart(){
        if GlobalDataHelper.instance.session == nil{
            self.goLogin()
            return
        }
        self.addGoodsToCart(GlobalDataHelper.instance.session, cartitemsid: self.dataItem!.id!, qty: "1")
    }
    func  goBack(){
        self.navigationController?.popViewControllerAnimated(true)
    }
    func pageTurn(control:UIPageControl){
        let size = imageScrollView.bounds.size
        let rect = CGRectMake(CGFloat(control.currentPage)*size.width, 0, size.width, size.height)
        imageScrollView.scrollRectToVisible(rect, animated: true)
    }
    override func viewWillAppear(animated: Bool){
        super.viewWillAppear(animated)
        navigationController?.navigationBarHidden = false
    }
    func queryGoodsByID(goodID:String!)->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(goodID, forKey: "id")
        request.requestStart("/pdp/getproductdetail", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                }
                self.dataItem = dic?.pareseDataToGoodItems()
                
                dispatch_async(dispatch_get_main_queue()){
                    self.layoutTopScrollView()
                    self.layoutBottomScrollView()
                }
            }
        })
        self.showProcess("加载中...")
    }
    func addGoodsToCart(sessionid:String!,cartitemsid:String!,qty:String)->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(sessionid, forKey: "sessionid")
        parameters.setObject(cartitemsid, forKey: "id")
        parameters.setObject("1", forKey: "qty")
        request.requestStart("/cart/add", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                }
                if (dic?["result"])! as! String == "0"{
                    dispatch_async(dispatch_get_main_queue()){
                        //添加成功处理
                         self.showTips("添加成功，您可以在购物车查看")
                    }
                }
                else{
                    dispatch_async(dispatch_get_main_queue(), {[weak self] in
                        self?.showTips(dic?["msg"] as? String)
                        })
                    
                }
            }
            else{
                dispatch_async(dispatch_get_main_queue()){
                    //添加成功处理
                    self.showTips("添加失败")
                }
            }
        })
        self.showProcess("处理中...")
    }
    func addGoodsToFavorite(sessionid:String!,id:String!)->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(sessionid, forKey: "sessionid")
        parameters.setObject(id, forKey: "id")
        request.requestStart("/favorite/add", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                }
                if (dic?["result"])! as! String == "0"{
                    dispatch_async(dispatch_get_main_queue()){
                        //添加成功处理
                        self.showTips("添加成功")
                    }
                }
                else{
                    dispatch_async(dispatch_get_main_queue(), {[weak self] in
                        self?.showTips(dic?["msg"] as? String)
                        })
                    
                }
            }
            else{
                dispatch_async(dispatch_get_main_queue()){
                    //添加成功处理
                    self.showTips("添加失败")
                }
            }
        })
        self.showProcess("处理中...")
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension GoodsDetailViewController:UIScrollViewDelegate{
    func scrollViewWillBeginDecelerating(scrollView: UIScrollView){
        if scrollView == topScrollView{
            if scrollView.contentOffset.y + scrollView.bounds.size.height >= scrollView.contentSize.height{
                self.showBottomContent()
            }
        }

    }
    func scrollViewDidEndDecelerating(scrollView: UIScrollView){
        if scrollView == self.imageScrollView{
            let point = scrollView.contentOffset
            let rect = self.imageScrollView.bounds
            pageControl.currentPage = Int(point.x/rect.size.width)
        }
    }
}